<?php
/**
 * 统一返回处理类（ajax）允许跨域
 *
 * 使用： **
 *      use api\ServerResponse;
 *      return ServerResponse::createBySuccess("成功");
 *      ServerResponse::createByError("断点失败了");
 */

namespace api;

use think\facade\Config;
use think\exception\HttpResponseException;
use think\Response;

class ServerResponse
{
    public static $successCode = true;
    public static $errorCode = false;

    //构造函数
    public function __construct($status,$msg = "",$data = [])
    {

        $result['code'] = $status;
        $msg ? $result['msg'] = $msg : null;
        $data ? $result['data'] = $data : null;

        $type                                   = $this->getResponseType();
        $header['Access-Control-Allow-Origin']  = '*';
        $header['Access-Control-Allow-Headers'] = 'X-Requested-With,Content-Type';
        $header['Access-Control-Allow-Methods'] = 'GET,POST,PATCH,PUT,DELETE,OPTIONS';
        $response                               = Response::create($result, $type)->header($header);
        throw  new HttpResponseException($response);
    }

    /**
     * 成功
     * @param $msg
     * @param null $data
     * @return ServerResponse
     */
    public static function createBySuccess($msg, $data = null){
        return new ServerResponse(self::$successCode, $msg,$data);
    }

    /**
     * 失败
     * @param $msg
     * @return ServerResponse
     */
    public static function createByError($msg){
        return new ServerResponse(self::$errorCode, $msg);

    }

    /**
     * 获取当前的response 输出类型
     * @access protected
     * @return string
     */
    private function getResponseType()
    {
        return Config::get('default_ajax_return');
    }
}
